package com.bw.common.http
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.SPUtils
import com.bw.common.const.Const
import com.bw.lib_base.base.BaseApp.Companion.context
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
object ApiServiceModule {
    /**
     * 检查当前是否有可用网络连接
     * 兼容 Android 6.0 (API 23) 及以上版本
     */
    fun isNetworkAvailable(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 新API（Android 6.0+）
            val network = connectivityManager.activeNetwork ?: return false
            val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false

            when {
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
                else -> false
            }
        } else {
            // 旧API（兼容Android 6.0以下）
            @Suppress("DEPRECATION")
            val networkInfo = connectivityManager.activeNetworkInfo
            networkInfo?.isConnected ?: false
        }
    }

    @Provides
    @Singleton
    fun providerOkHttpClient():OkHttpClient{
        val cacheSize = 50 * 1024 * 1024 // 50MB
        val cache = Cache(context.cacheDir, cacheSize.toLong())
        //获取OkHttpClient
        val parkClient = OkHttpClient.Builder()
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .connectTimeout(30, TimeUnit.SECONDS)
            .addInterceptor {chain->
                    val request = chain.request().newBuilder()
                        .addHeader("token", SPUtils.getInstance().getString("token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxODEwNzI1NzA3NyJ9.3TXdmcewuxHEGmmBDFy6vte9u4yLDovzqRso5xBosBw"))
                        .addHeader("accessId","0e8cc2f2974b4f3a948d7249366eec3e")
                        .build()
                    return@addInterceptor chain.proceed(request)
            }
            .addInterceptor { chain ->
                val request = chain.request()
                val cacheControl = if (isNetworkAvailable(context)) {
                    // 有网络：缓存5分钟
                    CacheControl.Builder()
                        .maxAge(5, TimeUnit.MINUTES)
                        .build()
                } else {
                    // 无网络：使用7天内缓存
                    CacheControl.Builder()
                        .maxStale(7, TimeUnit.DAYS)
                        .build()
                }

                val newRequest = request.newBuilder()
                    .cacheControl(cacheControl)
                    .build()

                chain.proceed(newRequest)
            }
//            .addNetworkInterceptor { chain ->
//                // 1. 先执行原始网络请求
//                val response = chain.proceed(chain.request())
//
//                // 2. 创建缓存控制策略：所有响应统一缓存2分钟
//                val cacheControl = CacheControl.Builder()
//                    .maxAge(5, TimeUnit.MINUTES)
//                    .build()
//
//                // 3. 修改响应头，添加统一的缓存控制
//                response.newBuilder()
//                    .header("Cache-Control", cacheControl.toString())
//                    .build()
//            }
            //缓存大小
            .cache(cache)
            .build()

        return parkClient
    }

    @Provides
    @Singleton
    fun providerRetrofit(client: OkHttpClient):Retrofit{
        val parkRetrofit = Retrofit.Builder()
            .baseUrl(Const.BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        return parkRetrofit
    }

}